const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3001;

// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.static('public'));

// 配置文件根目录
const CONFIG_DIR = path.join(__dirname, '..', 'src', 'core', 'config');

// 获取所有配置文件列表
app.get('/api/configs', (req, res) => {
    try {
        const files = fs.readdirSync(CONFIG_DIR)
            .filter(file => file.endsWith('.json'))
            .map(file => ({
                name: file.replace('.json', ''),
                filename: file,
                path: path.join(CONFIG_DIR, file)
            }));
        res.json(files);
    } catch (error) {
        res.status(500).json({ error: '读取配置文件列表失败: ' + error.message });
    }
});

// 获取特定配置文件内容
app.get('/api/config/:filename', (req, res) => {
    try {
        let filename = decodeURIComponent(req.params.filename);
        // 如果文件名已经包含.json，就不要再添加
        if (!filename.endsWith('.json')) {
            filename = filename + '.json';
        }
        const filePath = path.join(CONFIG_DIR, filename);
        
        if (!fs.existsSync(filePath)) {
            console.log('配置文件不存在:', filePath);
            return res.status(404).json({ error: '配置文件不存在: ' + filename });
        }
        
        const content = fs.readFileSync(filePath, 'utf8');
        const data = JSON.parse(content);
        res.json(data);
    } catch (error) {
        console.error('读取配置文件失败:', error);
        res.status(500).json({ error: '读取配置文件失败: ' + error.message });
    }
});

// 保存配置文件
app.post('/api/config/:filename', (req, res) => {
    try {
        let filename = decodeURIComponent(req.params.filename);
        // 如果文件名已经包含.json，就不要再添加
        if (!filename.endsWith('.json')) {
            filename = filename + '.json';
        }
        const filePath = path.join(CONFIG_DIR, filename);
        const data = req.body;
        
        // 备份原文件
        if (fs.existsSync(filePath)) {
            const backupPath = filePath + '.backup.' + Date.now();
            fs.copyFileSync(filePath, backupPath);
            console.log('创建备份文件:', backupPath);
        }
        
        // 保存新内容
        fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
        console.log('配置保存成功:', filePath);
        res.json({ success: true, message: '配置保存成功' });
    } catch (error) {
        console.error('保存配置文件失败:', error);
        res.status(500).json({ error: '保存配置文件失败: ' + error.message });
    }
});

// 生成配置文件的JSON Schema
app.get('/api/schema/:filename', (req, res) => {
    try {
        let filename = decodeURIComponent(req.params.filename);
        const originalFilename = filename;
        // 如果文件名已经包含.json，就不要再添加
        if (!filename.endsWith('.json')) {
            filename = filename + '.json';
        }
        const filePath = path.join(CONFIG_DIR, filename);
        
        if (!fs.existsSync(filePath)) {
            console.log('Schema - 配置文件不存在:', filePath);
            return res.status(404).json({ error: '配置文件不存在: ' + filename });
        }
        
        const content = fs.readFileSync(filePath, 'utf8');
        const data = JSON.parse(content);
        
        // 基于现有数据生成Schema
        const schema = generateSchema(data, originalFilename.replace('.json', ''));
        res.json(schema);
    } catch (error) {
        console.error('生成Schema失败:', error);
        res.status(500).json({ error: '生成Schema失败: ' + error.message });
    }
});

// 根据配置数据生成JSON Schema
function generateSchema(data, filename) {
    if (!Array.isArray(data) || data.length === 0) {
        return {
            type: "array",
            title: filename,
            items: { type: "object" }
        };
    }
    
    const sample = data[0];
    const properties = {};
    
    for (const [key, value] of Object.entries(sample)) {
        properties[key] = generatePropertySchema(key, value, filename);
    }
    
    return {
        type: "array",
        title: getConfigTitle(filename),
        items: {
            type: "object",
            properties: properties,
            required: Object.keys(properties)
        }
    };
}

function generatePropertySchema(key, value, filename) {
    const type = typeof value;
    
    switch (type) {
        case 'string':
            if (key === 'emoji') {
                return { 
                    type: "string", 
                    title: key,
                    description: "表情符号",
                    pattern: "^.{1,2}$"
                };
            }
            if (key === 'desc' || key === 'description') {
                return { 
                    type: "string", 
                    title: key,
                    description: "描述信息",
                    "format": "textarea"
                };
            }
            return { type: "string", title: key };
            
        case 'number':
            if (key === 'quality') {
                return { 
                    type: "integer", 
                    title: key,
                    description: "品质等级",
                    minimum: 1,
                    maximum: 5
                };
            }
            return { type: "number", title: key };
            
        case 'boolean':
            return { type: "boolean", title: key };
            
        case 'object':
            if (Array.isArray(value)) {
                if (value.length > 0) {
                    return {
                        type: "array",
                        title: key,
                        items: generatePropertySchema('item', value[0], filename)
                    };
                }
                return { type: "array", title: key, items: {} };
            } else {
                const subProperties = {};
                for (const [subKey, subValue] of Object.entries(value)) {
                    subProperties[subKey] = generatePropertySchema(subKey, subValue, filename);
                }
                return {
                    type: "object",
                    title: key,
                    properties: subProperties
                };
            }
            
        default:
            return { type: "string", title: key };
    }
}

function getConfigTitle(filename) {
    const titles = {
        'prop_道具': '道具配置',
        'prop_资源': '资源配置', 
        'prop_消耗品': '消耗品配置',
        'prop_盲盒': '盲盒配置',
        '游戏配置_equip': '装备配置',
        '游戏配置_sign': '签到配置',
        '游戏配置_血统表': '血统配置',
        '任务配置_loop': '循环任务配置',
        '技能数据_skillTable': '技能数据配置',
        'enemy_test': '测试敌人配置',
        'enemy_主神空间': '主神空间敌人配置',
        'enemy_十日终焉': '十日终焉敌人配置'
    };
    
    return titles[filename] || filename;
}

app.listen(PORT, () => {
    console.log(`配置管理服务器启动成功: http://localhost:${PORT}`);
});
